<template>
    <div class="add-cultural-info-container">
        <h2 class="section-title">添加文化资讯</h2>
        
        <!-- 文化资讯表单 -->
        <el-form :model="culturalInfoForm" :rules="rules" ref="culturalInfoFormRef" label-width="100px" class="cultural-info-form">
            <!-- 资讯标题 -->
            <el-form-item label="资讯标题" prop="title">
                <el-input v-model="culturalInfoForm.title" placeholder="请输入资讯标题"></el-input>
            </el-form-item>
            
            <!-- 专家姓名 -->
            <el-form-item label="专家姓名" prop="expertName">
                <el-input v-model="culturalInfoForm.expertName" placeholder="请输入专家姓名"></el-input>
            </el-form-item>
            
            <!-- 资讯图片 -->
            <el-form-item label="资讯图片" prop="image">
                <el-upload
                    class="cultural-info-image-uploader"
                    :action="null"
                    :http-request="handleUploadRequest"
                    :show-file-list="false"
                    :before-upload="beforeImageUpload">
                    <img v-if="culturalInfoForm.image" :src="imageUrl" class="cultural-info-image">
                    <el-icon v-else class="upload-icon"><Plus /></el-icon>
                </el-upload>
                <span class="form-item-tip">建议尺寸：800x600像素，大小不超过2MB</span>
            </el-form-item>
            
            <!-- 专家头像 -->
            <el-form-item label="专家头像" prop="expertAvatar">
                <el-upload
                    class="expert-avatar-uploader"
                    :action="null"
                    :http-request="handleAvatarUploadRequest"
                    :show-file-list="false"
                    :before-upload="beforeImageUpload">
                    <img v-if="culturalInfoForm.expertAvatar" :src="avatarUrl" class="expert-avatar">
                    <el-icon v-else class="upload-icon"><Plus /></el-icon>
                </el-upload>
                <span class="form-item-tip">建议尺寸：200x200像素，大小不超过1MB</span>
            </el-form-item>
            
            <!-- 资讯描述 -->
            <el-form-item label="资讯描述" prop="description">
                <el-input 
                    v-model="culturalInfoForm.description" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="请输入资讯描述，详细介绍文物背景与历史价值"
                ></el-input>
            </el-form-item>
            
            <!-- 专家点评 -->
            <el-form-item label="专家点评" prop="expertComment">
                <el-input 
                    v-model="culturalInfoForm.expertComment" 
                    type="textarea" 
                    :rows="3" 
                    placeholder="请输入专家点评内容"
                ></el-input>
            </el-form-item>
            
            <!-- 提交按钮 -->
            <el-form-item>
                <el-button type="primary" @click="submitForm">保存文化资讯</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
// 导入所需的组件和API
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import api from '@/assets/js/api.js';

const router = useRouter();
const culturalInfoFormRef = ref(null);

// 文化资讯表单数据
const culturalInfoForm = reactive({
    title: '', // 资讯标题
    expertName: '', // 专家姓名
    image: '', // 资讯图片
    expertAvatar: '', // 专家头像
    description: '', // 资讯描述
    expertComment: '' // 专家点评
});

// 表单验证规则
const rules = {
    title: [
        { required: true, message: '请输入资讯标题', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在2到100个字符之间', trigger: 'blur' }
    ],
    expertName: [
        { required: true, message: '请输入专家姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
    ],
    image: [
        { required: true, message: '请上传资讯图片', trigger: 'change' }
    ],
    expertAvatar: [
        { required: true, message: '请上传专家头像', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入资讯描述', trigger: 'blur' },
        { min: 10, max: 1000, message: '描述长度在10到1000个字符之间', trigger: 'blur' }
    ],
    expertComment: [
        { required: true, message: '请输入专家点评', trigger: 'blur' },
        { min: 10, max: 500, message: '点评长度在10到500个字符之间', trigger: 'blur' }
    ]
};

// 计算图片完整URL
const imageUrl = computed(() => {
    if (!culturalInfoForm.image) return '';
    return culturalInfoForm.image.startsWith('http') 
        ? culturalInfoForm.image 
        : `http://localhost:8080${culturalInfoForm.image}`; // 移除/files/
});

// 计算头像完整URL
const avatarUrl = computed(() => {
    if (!culturalInfoForm.expertAvatar) return '';
    return culturalInfoForm.expertAvatar.startsWith('http') 
        ? culturalInfoForm.expertAvatar 
        : `http://localhost:8080${culturalInfoForm.expertAvatar}`; // 移除/files/
});

// 图片上传处理
const handleUploadRequest = async (options) => {
    try {
        const result = await api.uploadFile(options.file);
        if (result.code === 200) {
            culturalInfoForm.image = result.data.url; // 修改这里，获取url属性
            ElMessage.success('图片上传成功');
        } else {
            ElMessage.error('图片上传失败');
        }
    } catch (error) {
        console.error('图片上传异常:', error);
        ElMessage.error('图片上传失败');
    }
};

// 专家头像上传处理
const handleAvatarUploadRequest = async (options) => {
    try {
        const result = await api.uploadFile(options.file);
        if (result.code === 200) {
            culturalInfoForm.expertAvatar = result.data.url; // 修改这里，获取url属性
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('头像上传失败');
        }
    } catch (error) {
        console.error('头像上传异常:', error);
        ElMessage.error('头像上传失败');
    }
};

// 上传前验证
const beforeImageUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
};

// 提交表单
const submitForm = () => {
    culturalInfoFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const result = await api.addCulturalInfo(culturalInfoForm);
                if (result.code === 200) {
                    ElMessage.success('文化资讯添加成功');
                    resetForm();
                    router.push('/home/cultural-info');
                } else {
                    ElMessage.error('添加失败: ' + result.message);
                }
            } catch (error) {
                console.error('添加文化资讯异常:', error);
                ElMessage.error('添加失败，请稍后重试');
            }
        } else {
            ElMessage.error('请检查表单信息');
        }
    });
};

// 重置表单
const resetForm = () => {
    culturalInfoFormRef.value.resetFields();
    Object.assign(culturalInfoForm, {
        title: '',
        expertName: '',
        image: '',
        expertAvatar: '',
        description: '',
        expertComment: ''
    });
};

// 返回列表页
const goBack = () => {
    router.push('/home/cultural-info');
};
</script>

<style scoped>
.add-cultural-info-container {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
}

.section-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 30px;
    color: #333;
    text-align: center;
}

.cultural-info-form {
    background: #fff;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 添加上传框样式 */
.form-item-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 12px;
}

/* 资讯图片上传框样式 */
.cultural-info-image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 180px;
    height: 180px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: border-color 0.3s;
}

.cultural-info-image-uploader:hover {
    border-color: #409EFF;
}

.cultural-info-image {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}

/* 专家头像上传框样式 */
.expert-avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 120px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: border-color 0.3s;
}

.expert-avatar-uploader:hover {
    border-color: #409EFF;
}

.expert-avatar {
    width: 118px;
    height: 118px;
    display: block;
    object-fit: cover;
}

.upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 40px;
    height: 40px;
}
</style>